package gui.del_object;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import objects.Adresse;
import objects.Personne;
import objects.Telephone;

import bdd_handler.AdresseDAO;
import bdd_handler.PersonneDAO;
import bdd_handler.TelephoneDAO;
import bdd_handler.bdd;

public class Del_Personne extends JFrame implements ActionListener{

	private static final long serialVersionUID = 1L;

	private JFrame parent;

	private Personne p;

	private AdresseDAO aDAO;
	private TelephoneDAO tDAO;
	private PersonneDAO pDAO;

	private JButton valider, annuler;

	public Del_Personne(JFrame parent, Personne personne)
	{
		//recuperation de la fenetre parente
		this.parent=parent;
		this.parent.setVisible(false);

		//construction de la fenetre
		this.p=personne;
		this.setTitle("Suppression de : "+p.getNom()+ " "+p.getPrenom());
		this.setSize(550,100);
		this.setResizable(false);
		JPanel pan=new JPanel();
		pan.setLayout(null);
		this.setContentPane(pan);

		//creation des DAOs
		bdd db=new bdd();
		aDAO=new AdresseDAO(db.getConnection());
		tDAO=new TelephoneDAO(db.getConnection());
		pDAO=new PersonneDAO(db.getConnection());


		//creation objets internes
		JLabel avert=new JLabel("Attention! Vous allez supprimer la personne '"+p.getNom()+" "+p.getPrenom()+"'. Cette action est irréversible.");
		valider=new JButton("supprimer");
		valider.addActionListener(this);
		annuler=new JButton("annuler");
		annuler.addActionListener(this);

		//placer les objets
		pan.add(avert);
		avert.setBounds(10,10,900,20);
		pan.add(annuler);
		annuler.setBounds(10, 40, 110, 20);
		pan.add(valider);
		valider.setBounds(130, 40, 110, 20);

		//action fermeture fenetre
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(
				new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						close();

					}
				}
				);
		//afficher la fenetre
		this.setVisible(true);
	}

	private void close(){
		this.parent.setVisible(true);
		this.dispose();
	}

	public void actionPerformed(ActionEvent e) {

		Object source=e.getSource();

		if(source==valider)
		{
			Adresse[] list_adresses=aDAO.findByPersonne(p);
			for(int i=0; i<list_adresses.length;i++)
				aDAO.delete(list_adresses[i]);
			Telephone[] list_telephones=tDAO.findByPersonne(p);
			for(int i=0; i<list_telephones.length;i++)
				tDAO.delete(list_telephones[i]);
			pDAO.delete(p);
			close();
		}
		if(source==annuler)
		{
			close();
		}
	}
}
